package com.yonyou.gmcc.gateway.wechat.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.tomcat.util.http.MimeHeaders;
import org.marketing.common.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.netflix.zuul.context.RequestContext;
import com.yonyou.gmcc.gateway.wechat.common.CommonConstants;
import com.yonyou.gmcc.gateway.wechat.entity.UserVo;
import com.yonyou.gmcc.gateway.wechat.service.interfaces.WechatApiServiceInterface;

@Component
public class TokenCheck {
	private static Logger logger = Logger.getLogger(TokenCheck.class);
	
	@Autowired
	private WechatApiServiceInterface wechatApiServiceInterface;

	public boolean check(HttpServletRequest req, HttpServletResponse res) {
	    logger.info("转发请求到微服务，验证cookie中是否包含openid，并取得openid并写入头转发到其他微服务");
		UserVo user = null;
		try {
			user = getCookieUserInfo(req);
		} catch (Exception e1) {
			logger.debug("getUserinfo exception:" + e1.getMessage());
		}
		if (user == null) {
			logger.debug("--TokenCheck,user==null,RESPONSE_NON_LOGIN");
			res.setStatus(CommonConstants.RESPONSE_NON_LOGIN);
			return false;
		} else {
			String openId = user.getOpenId();
			logger.debug("----cookie-openid=" + openId);
			String userId = user.getUserid();
			logger.debug("----cookie-userId=" + userId);
			if (CheckUtil.NullOrEmpty(openId)&&CheckUtil.NullOrEmpty(userId)) {
				logger.debug("----cookie-openid null,RESPONSE_NON_LOGIN" + openId);
				logger.debug("----cookie-userId null,RESPONSE_NON_LOGIN" + userId);
				res.setStatus(CommonConstants.RESPONSE_NON_LOGIN);
				return false;
			}
//			writeHeader(req, CommonConstants.HEAD_OPENID_NAME, openId);
			RequestContext requestContext = RequestContext.getCurrentContext();
	        requestContext.addZuulRequestHeader(CommonConstants.HEAD_OPENID_NAME,openId);
	        requestContext.addZuulRequestHeader(CommonConstants.HEAD_USER_ID,userId);
		}
		return true;
	}

	public void writeOpenidHeader(HttpServletRequest req, String value) {
	    logger.info("写入openId开始:"+value);
	    String userId = wechatApiServiceInterface.selectUserIdByOpenId(value);
	    logger.info("写入userId开始:"+userId);
		Object obj1 = ReflectionUtils.getFieldValue(req, "request");
		Object obj2 = ReflectionUtils.getFieldValue(obj1, "request");
		Object obj3 = ReflectionUtils.getFieldValue(obj2, "coyoteRequest");
		org.apache.coyote.Request r = (org.apache.coyote.Request) obj3;
		MimeHeaders m = r.getMimeHeaders();
		m.addValue(CommonConstants.HEAD_OPENID_NAME).setString(value);
		m.addValue(CommonConstants.HEAD_USER_ID).setString(userId);
        logger.info("写入openId结束:"+m.getHeader(CommonConstants.HEAD_OPENID_NAME));
        logger.info("写入userId结束:"+m.getHeader(CommonConstants.HEAD_USER_ID));
	}

	private UserVo getCookieUserInfo(HttpServletRequest request) throws Exception {
		UserVo user = new UserVo();
		user.setOpenId(CookieUtil.getOpenid(request));
		user.setUserid(CookieUtil.getUserId(request));
		return user;
	}

}
